<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>
    <button class="btn">点我</button>
    <script>

        // 实现发布订阅 事件总线
        // 订阅  发布
        class MyEventBus {
            constructor() {
                // {"malu":[f1,f2]}
                this.eventMap = {}
            }

            on(eventName, eventFn) {
                let eventFns = this.eventMap[eventName]
                if (!eventFns) {
                    eventFns = [];
                    this.eventMap[eventName] = eventFns
                }
                eventFns.push(eventFn)
            }

            off(eventName, eventFn) {
                let eventFns = this.eventMap[eventName];
                if (!eventFns) return;
                // {eat:[f1,f2,f3...]}
                for (let i = 0; i < eventFns.length; i++) {
                    let fn = eventFns[i];
                    if (fn === eventFn) {
                        eventFns.splice(i, 1)
                        break;
                    }

                }
                // 如果eventFns已经清空了
                if (eventFns.length === 0) {
                    delete this.eventMap[eventName]
                }
            }

            emit(eventName, ...args) {
                let eventFns = this.eventMap[eventName];
                if (!eventFns) return;
                eventFns.forEach(fn => {
                    fn(...args)
                })
            }
        }


        // 使用过程
        const eventBus = new MyEventBus()

        // 实现订阅
        eventBus.on("malu", (name, age, height) => {
            console.log("malu事件监听器01:", name, age, height);
        })

        let eat = (name, age, height) => {
            console.log("eat事件监听器02", name, age, height);
        };
        eventBus.on("eat", eat)


        setTimeout(() => {
            eventBus.off("eat", eat)
        }, 3000)


        const btn = document.querySelector(".btn")
        btn.onclick = function () {
            // 发布
            // eventBus.emit("malu", "wc", 18, 1.88)
            eventBus.emit("eat", "wc", 18, 1.88)
        }

    </script>

</body>

</html>